package com.hiwan.unions.activity.main;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.view.View;

import com.hiwan.unions.R;
import com.hiwan.unions.activity.base.RootActivity;
import com.hiwan.unions.application.interfac.IService;
import com.hiwan.unions.application.request.CallServer;
import com.hiwan.unions.application.request.ConstsNet;
import com.hiwan.unions.application.request.HttpListener;
import com.hiwan.unions.application.service.LocalService;
import com.hiwan.unions.util.CheckUtils;
import com.hiwan.unions.util.ExampleUtil;
import com.hiwan.unions.util.JsonUtil;
import com.hiwan.unions.util.Utils;
import com.hiwan.unions.view.CircleTextProgressbar;
import com.hiwan.unions.view.CustomVideoView;
import com.hiwan.unions.view.dialog.LuanchDialog;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.json.JSONObject;

import java.util.List;


public class LuanchActivity extends RootActivity implements HttpListener<JSONObject> {
    private MyServiceConnection conn = null;
    private IService iService = null;
    private Intent serviceIntent = null;
    private CustomVideoView videoview;
    private CircleTextProgressbar progressbar;
    protected SharedPreferences userInfoC;

    @Override
    protected int getLayout() {
        title = false;
        return R.layout.activity_luanch;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onViewCreated() {
        super.onViewCreated();
        Luanch();
    }

    private void premission() {
        AndPermission.with(this)
                .requestCode(100)
                .permission(
                        // 多个权限，以数组的形式传入。
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .callback(this)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(LuanchActivity.this, rationale)
                                .show();
                    }
                })
                .start();

    }

    private void show() {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(ConstsNet.show_android);
        CallServer.getRequestInstance().add(this, 0, request, this, true);
    }

    /**
     * <p>权限全部申请成功才会回调这个方法，否则回调失败的方法。</p>
     * 日历权限申请成功；使用@PermissionYes(RequestCode)注解。
     *
     * @param grantedPermissions AndPermission回调过来的申请成功的权限。
     */
    @PermissionYes(100)
    private void getCalendarYes(@NonNull List<String> grantedPermissions) {
        conn = new MyServiceConnection();
        serviceIntent = new Intent(this, LocalService.class);
        bindService(serviceIntent, conn, Context.BIND_AUTO_CREATE);
        show();
    }


    /**
     * <p>只要有一个权限申请失败就会回调这个方法，并且不会回调成功的方法。</p>
     * 日历权限申请失败，使用@PermissionNo(RequestCode)注解。
     *
     * @param deniedPermissions AndPermission回调过来的申请失败的权限。
     */
    @PermissionNo(100)
    private void getCalendarNo(@NonNull List<String> deniedPermissions) {
        Utils.tis(deniedPermissions, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //播放
        videoview.start();
        progressbar.start();
    }

    // 渐变展示启动屏
    public void Luanch() {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(this, Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.media));
        String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // 播放时长单位为毫秒
        progressbar = (CircleTextProgressbar) findViewById(R.id.progressbar);
        progressbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                premission();
                progressbar.stop();
                videoview.pause();
            }
        });
        // 设置倒计时时间毫秒，默认3000毫秒。
        progressbar.setTimeMillis(Long.parseLong(duration));
        progressbar.setOutLineColor(Color.TRANSPARENT);
        progressbar.setInCircleColor(Color.WHITE);
        progressbar.setProgressColor(getResources().getColor(R.color.apptheme));
        progressbar.setProgressLineWidth(5);
        progressbar.setProgressType(CircleTextProgressbar.ProgressType.COUNT);

        videoview = (CustomVideoView) findViewById(R.id.videoview);
        //设置播放加载路径
        videoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.media));
        //播放
        videoview.start();
        progressbar.start();
        //循环播放folderrollpicture/list
        videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                premission();
            }
        });
    }

    @Override
    public void onSucceed(int what, Response<JSONObject> response) {
        JSONObject jsonObject = response.get();
        jsonObject = JsonUtil.getJSONObject(jsonObject, "data");
        String code = JsonUtil.getString(jsonObject, "version");
        if (CheckUtils.getExtensionName(code, ExampleUtil.GetVersion(LuanchActivity.this))) {
            MainActivity.startPreview(this);
            finish();
        } else {
            new LuanchDialog(LuanchActivity.this).show();
        }
    }

    @Override
    public void onFailed(int what, int errCode, String networkMillis, boolean type) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        progressbar.stop();
        videoview.pause();
    }

    //
    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //拿到在服务里面实现了IService接口的Binder对象
            iService = (IService) service;
            Logger.i("IService  " + "我被拿到了");
            iService.invokeServiceMethod(true);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (conn != null) {
            unbindService(conn);
            conn = null;
        }
    }
}
